package com.dtsz.m2.volley.httpUtil;

import android.graphics.Bitmap;
import android.util.Log;
import android.widget.ImageView;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.dtsz.m2.volley.VolleyApplication;
import com.dtsz.m2.volley.httpUtil.interfase.HUCCallBackInterfase;
import com.dtsz.m2.volley.httpUtil.interfase.HUCDataAnalysisInterfase;
import com.dtsz.m2.volley.httpUtil.interfase.HUCRequestInterfase;
import com.dtsz.m2.volley.httpUtil.rewrite.HUCImageRequest;
import com.dtsz.m2.volley.httpUtil.rewrite.HUCStringRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;


public final class HUCRequest implements HUCRequestInterfase {
    private RequestQueue mQueue;
    private ImageLoader mImageLoader;
    private static HUCRequest commonRequest;
    private HUCDataAnalysisInterfase hucDataAnalysisInterfase;

    public static final int SUCCESS_CODE = 0x000000;
    public static final int SUCCESS_CODE1 = 0x000001;
    public static final int SUCCESS_CODE2 = 0x000002;

    public static final int FAIL_CODE1 = 0x199999;

    public static HUCRequest getInstance() {
        if (commonRequest == null) {
            commonRequest = new HUCRequest();
        }
        return commonRequest;
    }

    public HUCRequest() {
        super();
        mQueue = VolleyApplication.getMyApplication().getRequestQueue();
        mImageLoader = VolleyApplication.getMyApplication().getImageLoader();
        hucDataAnalysisInterfase = HUCDataAnalysis.getInstance();
    }

    @Override
    public void executeStr(final HUCCallBackInterfase httpLogicAbst,
                           final Class<?> classs, final int inputType, int method, String url,
                           Map<String, String> requestParameter, final boolean isflag) {
        HUCStringRequest myStringRequest = new HUCStringRequest(method, url,
                new Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        if (inputType == 100) {
                            httpLogicAbst.onSuccessfulStrType(inputType, response);
                        } else {
                            JSONObject json = null;
                            try {
                                json = new JSONObject(response);
                                int code = json.optInt("code");
                                String dataList = json.optString("datalist");
                                if (SUCCESS_CODE2 == code) {
                                    httpLogicAbst.onSuccessfulStrType(inputType, dataList);
                                } else if (SUCCESS_CODE == code) {
                                    httpLogicAbst.onSuccessfulStrType(inputType, dataList);
                                } else if (FAIL_CODE1 == code) {
                                    httpLogicAbst.onErrorLogin(inputType);
                                } else {
                                    httpLogicAbst.onSuccessfulStrType(inputType,
                                            hucDataAnalysisInterfase.parseJsonList(classs,
                                                    response, isflag));
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                    }
                }, new ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                httpLogicAbst.onErrorResponse(inputType, error);
            }
        }, requestParameter);
        /* 解决重复请求问题 */
        myStringRequest.setRetryPolicy(new DefaultRetryPolicy(60000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT) {

            @Override
            public int getCurrentRetryCount() {
                /*
                 * Volley默认尝试两次，MAX=1,count=0;count<=MAX;count++;count=2时，
                 * 表示当前已经重复请求两次，就不会再第三次重复请求，从而屏蔽掉Volley的自动重复请求功能；
                 */
                return 1;
            }

        });
        mQueue.add(myStringRequest);
    }

    @Override
    public void executeStr(HUCCallBackInterfase httpLogicAbst,
                           final Class<?> classs, int inputType, int method, String url, boolean isFlag) {
        executeStr(httpLogicAbst, classs, inputType, method, url,
                new HashMap<String, String>(), isFlag);
    }

    @Override
    public void executeImageDownload(final HUCCallBackInterfase httpLogicAbst,
                                     final int inputType, String url) {
        HUCImageRequest myImageRequest = new HUCImageRequest(url,
                new Listener<Bitmap>() {

                    @Override
                    public void onResponse(Bitmap response) {
                        httpLogicAbst.onSuccessfulBitampType(inputType,
                                response);
                    }

                }, new ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                httpLogicAbst.onErrorResponse(inputType, error);
            }
        });
        mQueue.add(myImageRequest);
    }

    @Override
    public void executeImageDownloadAndCache(String url, ImageView imageView,
                                             int defaultImageResId, int errorImageResId) {
        mImageLoader.get(url, ImageLoader.getImageListener(imageView,
                defaultImageResId, errorImageResId));

    }

    @Override
    public void executeImageDownloadAndCache(String url, ImageView imageView,
                                             int defaultImageResId, int errorImageResId, int maxWidth,
                                             int maxHeight) {
        mImageLoader.get(url, ImageLoader.getImageListener(imageView,
                defaultImageResId, errorImageResId), maxWidth, maxHeight);
    }

    @Override
    public void cancelAll() {
        mQueue.cancelAll(this);
    }

    @Override
    public void jsonMap(final HUCCallBackInterfase httpLogicAbst, final int inputType, int method, String url,
                        Map<String, String> requestParameter) {
        HUCStringRequest myStringRequest = new HUCStringRequest(method, url,
                new Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        httpLogicAbst.onSuccessfulStrType(inputType, response);
                    }
                }, new ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                httpLogicAbst.onErrorResponse(inputType, error);
            }
        }, requestParameter);
        /* 解决重复请求问题 */
        myStringRequest.setRetryPolicy(new DefaultRetryPolicy(60000, 0, 1f) {

            @Override
            public int getCurrentRetryCount() {
                /*
                 * Volley默认尝试两次，MAX=1,count=0;count<=MAX;count++;count=2时，
                 * 表示当前已经重复请求两次，就不会再第三次重复请求，从而屏蔽掉Volley的自动重复请求功能；
                 */
                return 1;
            }

        });
        mQueue.add(myStringRequest);
    }


}
